// pages/order/order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [],
    filteredOrderList: [],
    searchText: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const orderList = wx.getStorageSync('orderList') || [];
    this.setData({ orderList, filteredOrderList: orderList });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onSearchInput(e) {
    const searchText = e.detail.value.trim();
    const orderList = this.data.orderList;
    if (!searchText) {
      this.setData({ searchText, filteredOrderList: orderList });
      return;
    }
    // 支持按商品名、类型、描述、订单状态等搜索
    const filteredOrderList = orderList.filter(order =>
      order.items.some(item =>
        (item.name && item.name.indexOf(searchText) !== -1) ||
        (item.type && item.type.indexOf(searchText) !== -1) ||
        (item.desc && item.desc.indexOf(searchText) !== -1)
      ) ||
      (order.status && order.status.indexOf(searchText) !== -1)
    );
    this.setData({ searchText, filteredOrderList });
  },

  deleteOrder(e) {
    const id = e.currentTarget.dataset.id;
    let orderList = this.data.orderList.filter(order => order.id != id);
    wx.setStorageSync('orderList', orderList);
    // 重新过滤，保持搜索结果同步
    const searchText = this.data.searchText;
    let filteredOrderList = orderList;
    if (searchText) {
      filteredOrderList = orderList.filter(order =>
        order.items.some(item =>
          (item.name && item.name.indexOf(searchText) !== -1) ||
          (item.type && item.type.indexOf(searchText) !== -1) ||
          (item.desc && item.desc.indexOf(searchText) !== -1)
        ) ||
        (order.status && order.status.indexOf(searchText) !== -1)
      );
    }
    this.setData({ orderList, filteredOrderList });
    wx.showToast({
      title: '订单已删除',
      icon: 'success'
    });
  }
})